<?php

class FtpConnect {

    private $connectionHandler;
    private $maxAttempts = 3;

    public function __construct($server, $user, $password) {

        $this->connectionHandler = ftp_connect($server);

        if (!$this->connectionHandler)
            throw new Exception("Cannot connect to '$server'");

        if (!ftp_login($this->connectionHandler, $user, $password))
            throw new Exception("Cannot login to '$server' with username '$user'");
    }

    public function __destruct() {
        ftp_close($this->connectionHandler);
    }

    public function chDir($dirname) {
        if (!ftp_chdir($this->connectionHandler, $dirname))
            throw new Exception("Cannot change dir to '$localFilename'");
    }

    public function uploadFile($localFilename, $remoteFilename = null, $attemptNumber = 1) {

        File::checkExistsAndReadable($localFilename);

        if ($remoteFilename === null) $remoteFilename = basename($localFilename);

        if (!($err = ftp_put($this->connectionHandler, $remoteFilename, $localFilename, FTP_BINARY))) {
            if ($attemptNumber < $this->maxAttempts) {
                $this->uploadFile($localFilename, $remoteFilename, $attemptNumber + 1);
            } else {
                throw new Exception("Transfer '$localFilename' failed. Error: $err");
            }
        }
    }
}

?>
